import { Client, CreateRoomConfig, Player, Room } from "../GOBE/GOBE";
import { GameInitInfo, PlayerInitInfo, RoomType, SceneType } from "./CommonValue";
import GameUtils from "./GameUtils";

export class Global {
    // 私有静态属性，用于存储单例实例
    private static _instance: Global | null = null;

    // 定义实例属性，对应不同类型的实例
    public client: Client | null = null;
    public room: Room | null = null;
    public gameId: string = "245150415728390309";
    // 匹配模式
    public matchRule: string = '0';
    public group: any | null = null;
    public player: Player | null = null;
    public playerId: string | null = null;


    public planeSize: number = 15;            // 飞机尺寸，圆形，半径为15像素
    public planeMaxHp: number = 2;            // 飞机最大生命值
    public bulletSize: number = 4;            // 子弹尺寸，圆形，半径为4像素
    public bulletStepPixel: number = 30;     // 子弹步长，30像素每秒
    public bgMaxX: number = 780;              // 飞行背景x最大值
    public bgMinX: number = 20;               // 飞行背景x最小值
    public bgMaxY: number = 420;              // 飞行背景y最大值
    public bgMinY: number = 20;               // 飞行背景y最小值



    public playerName: string = "";
    public isOnlineMatch: boolean = false;
    public roomType: RoomType = RoomType.OneVOne;    // 房间类型，区分1v1、2v2、3v1类型房间，重连时用\
    isConnected: boolean;


    public unhandleFrames: GOBE.RecvFrameMessage[] = []; //未处理的帧
    public unProcessedServerInfo: GOBE.RecvFromServerInfo[] = []; //未处理的实时消息
    // public jumpType: number = 0; // 跳转方式 1-小队跳转 2-房间跳转


    public roomInfo: GameInitInfo = null;

    // 私有构造函数，防止外部直接实例化
    private constructor() { }

    // 静态方法，用于获取单例实例
    public static Inst(): Global {
        if (!Global._instance) {
            // 若实例不存在，则创建新实例
            Global._instance = new Global();
        }
        return Global._instance;
    }

    public Init(openId: string) {
        // 实例化Client对象
        this.client = new window.GOBE.Client({
            appId: this.gameId,              // 应用ID，具体获取可参见准备游戏信息
            openId: openId,             // 玩家ID，区别不同用户
            clientId: '1680498256645252672',           // 客户端ID，具体获取可参见准备游戏信息
            clientSecret: 'F19D2F41E1BA8B5126B1F9FE186D3C337D36DC79EF49E2676390C3A045C5B957', // 客户端密钥，具体获取可参见准备游戏信息
            accessToken: 'DQEDANbtGc0N3cEKbe1bBZaXa0Spc6vN79l2PizhczedCxvq1WHRRmaXZGqqQqg4at9sMOzxP2w68crh3JIn2Ez8kOtoQDgEJ4tVCg==',  // AGC接入凭证(推荐)
            platform: window.GOBE.PlatformType.WEB,          // 平台类型（选填）
            cerPath: '{cerPath}',          // 证书绝对路径（选填）
        });
        this.InitEvent();


        // 调用Client.init方法进行初始化
        this.client.init().then((client) => {
            // 已完成初始化请求，具体初始化结果通过onInitResult回调获取
            this.playerId = client.playerId;
            // demo生成昵称保存到global
            this.playerName = GameUtils.MockPlayerName();

        }).catch((err) => {
            // 初始化请求失败，重新初始化或联系华为技术支持
            console.error(err);
        });
    }

    InitEvent() {
        // 注册Client.onInitResult监听回调
        this.client.onInitResult(this.OnInitResult.bind(this));
    }

    OnInitResult(resultCode: number) {
        {
            if (resultCode === window.GOBE.ErrorCode.COMMON_OK) {
                this.playerId = this.client.playerId;
                if (this.client.lastRoomId || this.client.lastGroupId) {
                    if (this.client.lastRoomId) {
                        this.JoinRoom(this.client.lastRoomId);
                    }
                } else {
                    cc.director.loadScene(SceneType.HAll);
                }
            } else {
                // 初始化失败，重新初始化或联系华为技术支持
                console.error("初始化失败，错误码：" + resultCode);

            }
        }
    }

    // OnMatch(res) {
    //     Util.printLog('触发匹配');
    //     Util.printLog(global.group.customGroupProperties);
    //     if (res.rtnCode === 0) {
    //         Util.printLog('在线匹配成功:' + res.room);
    //         global.room = res.room;
    //         global.player = res.room.player;
    //         global.group = global.client.group;
    //         cc.director.loadScene(config.asymmetric ? "asymmetricroom" : "teamroom");
    //         Reloading.close();
    //     } else {
    //         Util.printLog("在线匹配失败" + Util.errorMessage(res));
    //         Reloading.close();
    //     }
    // }

    CreateRoom(createRoomConfig: CreateRoomConfig) {
        return new Promise((resolve, reject) => {
            // 实例化Room对象
            this.client.createRoom(
                createRoomConfig,
                { customPlayerStatus: 0, customPlayerProperties: '' }).then((room: Room) => {
                    // 创建房间中
                    this.room = room;
                    this.player = room.player;
                    // console.warn('room', room);
                    cc.director.loadScene(SceneType.ROOM);
                    // this.room.onJoin((playerInfo) => {
                    //     // 判断是否为当前玩家加入房间
                    //     if (playerInfo.playerId === this.room.playerId) {
                    //         // 创建并加入房间成功，做相关游戏逻辑处理
                    //         console.warn("当前玩家加入房间", playerInfo);

                    //     } else {
                    //         // 其他玩家加入房间
                    //         console.warn("其他玩家加入房间", playerInfo);
                    //     }
                    // });
                    resolve(room);
                }).catch((e) => {
                    // 创建房间失败
                    reject(e);

                });
        })

    }

    JoinRoom(roomId: string) {
        return new Promise((resolve, reject) => {
            // 房间ID或者房间短码
            const roomIdentity = roomId;
            // 当加入房间失败时，该玩家可通过如下方法收到失败事件通知
            this.client.onJoinRoomFailed((error) => {
                console.warn('加入房间失败', error);
            });
            this.client.joinRoom(roomIdentity,
                { customPlayerStatus: 0, customPlayerProperties: '' }).then((room: Room) => {
                    // 加入房间中
                    this.room = room;
                    this.player = room.player;
                    console.warn(room);
                    GameUtils.Log('玩家id ：' + this.player.playerId + '  房主id ：' + this.room.ownerId);

                    let roomProp = JSON.parse(this.room.customRoomProperties);
                    this.isOnlineMatch = roomProp.isOnlineMatch;
                    if (Global.Inst().room.isSyncing) {
                        cc.director.loadScene(SceneType.GAME);
                        return
                    }
                    if (roomProp.roomType !== undefined) {
                        this.roomType = roomProp.roomType;
                        if (roomProp.roomType == RoomType.OneVOne + "") {
                            // this.jumpType = RoomType.OneVOne;
                            cc.director.loadScene(SceneType.ROOM);
                        }
                    }
                    resolve(room);
                }).catch((e) => {
                    // 加入房间失败
                    reject(e);
                });
        })

    }

    MatchRoom() {
        return new Promise((resolve, reject) => { // Reloading.open("匹配中。。。", false);
            let customRoomProp = {
                planeSize: this.planeSize,          // 飞机尺寸，圆形，半径为15像素
                planeHp: this.planeMaxHp,           // 飞机最大生命值
                bulletSize: this.bulletSize,        // 子弹尺寸，圆形，半径为4像素
                bulletSpeed: this.bulletStepPixel,  // 子弹速度，400像素每秒
                bgMaxX: this.bgMaxX,                // 飞行背景x最大值
                bgMaxY: this.bgMaxY,                 // 飞行背景y最大值
                roomType: this.roomType
            }
            this.client.matchRoom({
                matchParams: {
                    'matchRule': Global.Inst().matchRule,
                    'matchRule2': Global.Inst().matchRule,
                },
                roomType: "1",
                customRoomProperties: JSON.stringify(customRoomProp),
                maxPlayers: 4,
            }, { customPlayerStatus: 0, customPlayerProperties: "" }).then((room) => {
                GameUtils.Log("房间匹配成功");
                console.warn(room);
                this.room = room;
                this.player = room.player;
                resolve(room);
                //转入room场景
                cc.director.loadScene(SceneType.ROOM);
            }).catch((e) => {
                reject(e);
                // Dialog.open("提示", "房间匹配失败" + Util.errorMessage(e));
            });
        })
    }

    public Destory() {
        // 销毁实例
        this.client.destroy();
    }
}
